import axios from 'axios';
import config from '../../config.json';
import {DeviceEventEmitter} from 'react-native';
import {UserState} from '../reducers/user';

class HttpClient {
  constructor() {
    this.config = {
      timeout: 5 * 1000,
      cancelToken: axios.CancelToken.source.token,
      baseURL: config.httpClient.host,
    };
    this.token = '';
    this.client = axios.create(this.config);
    this.client.defaults.headers.post['Content-Type'] = 'application/json';
    this.ignoreList = [
      '/admin/auth/token',
      '/device',
      '/web/send-email-code',
      '/web/dentist/new',
      '/web/vendor/new',
      '/web/country',
      '/web/search-vendor',
      '/web/forget',
      '/web/reset',
      '/web/category/a',
      '/web/dent/order-selection',
    ];

    this.configInterceptors();
  }

  setAuthToken = token => {
    this.token = token;
  };

  cancelToken = cancel => {
    this.cancel = cancel;
  };

  cancelRequest() {
    this.cancel();
  }

  requestInterceptor = requestConfig => {
    if (!this.ignoreList.includes(requestConfig.url)) {
      requestConfig.headers.Authorization = `Bearer ${this.token}`;
    }
    return requestConfig;
  };

  responseInterceptor = response => response;

  configInterceptors = () => {
    this.client.interceptors.request.use(this.requestInterceptor);

    this.client.interceptors.response.use(this.responseInterceptor, error => {
      if (error.response) {
        if (error.response.status === 401) {
          DeviceEventEmitter.emit(UserState.EXPIRED);
        }
      }
      return Promise.reject(error); // 返回接口返回的错误信息
    });
  };

  get(url) {
    return this.client.get(url, this.config);
  }

  post(url, data) {
    return this.client.post(url, data, this.config);
  }

  put(url, data) {
    return this.client.put(url, data, this.config);
  }

  delete(url) {
    return this.client.delete(url, this.config);
  }

  patch(url, data) {
    return this.client.patch(url, data);
  }

  encodeParams = obj => {
    if (!obj) {
      return '';
    }
    return Object.keys(obj)
      .map(function (key) {
        return ''
          .concat(encodeURIComponent(key), '=')
          .concat(encodeURIComponent(obj[key]));
      })
      .join('&');
  };
}

export default new HttpClient();
